<template>
  <div class="cart">
    <div v-show="cartInfoList.length">
      <h3 class="all-goods">全部商品 12</h3>
      <ul class="goods-title">
        <li class="gt-check-all">
          <div>
            <input
              type="checkbox"
              :checked="isAllChecked"
              @click.prevent="checkAll"
            />
          </div>
          全选
        </li>
        <li class="gt-goods">商品</li>
        <li class="gt-price">单价</li>
        <li class="gt-count">数量</li>
        <li class="gt-num">小计</li>
        <li class="gt-del">操作</li>
      </ul>
      <div
        class="goods-wrap"
        v-for="(goodsInfo, index) in cartInfoList"
        :key="goodsInfo.id"
      >
        <div class="goods-little-title">
          <div>尚品汇自营旗舰店<i class="jd-dog"></i></div>
          <div class="coupon"></div>
        </div>
        <div
          class="goods-content"
          :class="{ 'goods-active': goodsInfo.isChecked }"
        >
          <div class="check-one">
            <input
              type="checkbox"
              :checked="goodsInfo.isChecked"
              @click.prevent="
                checkOrnotCheck(index, goodsInfo.skuId, !goodsInfo.isChecked)
              "
            />
          </div>
          <div class="goods-img-wrap">
            <img :src="goodsInfo.imgUrl" alt="" />
          </div>
          <div class="goods-msg">
            {{ goodsInfo.skuName }}
          </div>
          <div class="goods-price">￥{{ goodsInfo.skuPrice }}</div>
          <div class="goods-count">
            <button
              @click="subOrAddGoodsNum(goodsInfo.skuId, goodsInfo, -1)"
              :disabled="goodsInfo.skuNum <= 1"
            >
              -
            </button>
            <input
              type="text"
              :value="goodsInfo.skuNum"
              @blur="inputHandle($event, goodsInfo.skuNum, goodsInfo)"
              @keyup.enter="inputHandle($event, goodsInfo.skuNum, goodsInfo)"
            />
            <button
              @click="subOrAddGoodsNum(goodsInfo.skuId, goodsInfo, 1)"
              :disabled="goodsInfo.skuNum >= 100"
            >
              +
            </button>
          </div>
          <div class="goods-sum">
            ￥{{ goodsInfo.skuNum * goodsInfo.skuPrice }}
          </div>
          <div class="goods-opation" @click="open(goodsInfo.skuId, index)">
            删除
          </div>
        </div>
      </div>

      <div class="goods-settlement">
        <div class="settlement-left">
          <div>
            <div>
              <input
                type="checkbox"
                :checked="isAllChecked"
                @click.prevent="checkAll"
              />
            </div>
            全选
          </div>
          <div class="settlement-del" @click="delFatchGoods">
            删除选中的商品
          </div>
        </div>
        <div class="settlement-right">
          <div>已选择 {{ totalAllCheck }} 件商品</div>
          <div>
            总价（不含运费）<span>￥{{ totalPrice }}</span>
          </div>
          <div class="settlement-button">
            <button @click="toTrade">去结算</button>
          </div>
        </div>
      </div>
    </div>
    <div class="empty" v-show="!cartInfoList.length">
      <h3>购物车空空如也</h3>
      <img src="./images/empty.751bed26.gif" alt="" />
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import {
  reqGetCartList,
  reqCheckCart,
  reqBatchCheckCart,
  reqPostAddToCart,
  reqBatchDelCart,
  reqDelSigleGoods,
} from '@/api/cartAPI'

export default {
  name: 'ZCart',
  data() {
    return {
      cartInfoList: [],
      skuNum: 1,
      flag: true,
    }
  },
  mounted() {
    this.getCartList()
  },
  computed: {
    // 已选择商品数量
    totalAllCheck() {
      return this.cartInfoList.reduce((pre, cur) => pre + cur.isChecked, 0)
    },
    // 所有的商品id列表
    skuIdList() {
      return this.cartInfoList.map((info) => {
        return info.skuId
      })
    },

    // 是否全选
    isAllChecked() {
      return this.cartInfoList.every((info) => info.isChecked)
    },
    // 总价
    totalPrice() {
      return this.cartInfoList.reduce(
        (pre, cur) => pre + (cur.isChecked ? cur.skuPrice * cur.skuNum : 0),
        0
      )
    },
  },
  methods: {
    ...mapMutations('cart', ['ADDGOODSLIST']),
    //toTrade 去结算页
    toTrade() {
      this.ADDGOODSLIST(this.cartInfoList)
      this.$router.push('/trade')
    },

    // 删除单条数据
    open(skuId, index) {
      this.$confirm('商品将从购物车中移除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await reqDelSigleGoods(skuId)
          this.cartInfoList.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 请求数据
    async getCartList() {
      const res = await reqGetCartList()
      if (!res.length) return
      this.cartInfoList = res[0].cartInfoList
    },
    // 切换选中状态
    async checkOrnotCheck(index, id, isChecked) {
      if (!this.flag) return
      this.flag = false
      await reqCheckCart(id, +isChecked)
      this.cartInfoList[index].isChecked = +isChecked
      this.flag = true
    },
    // 手动输入数量
    async inputHandle(e, oldValue, goodsInfo) {
      const value = e.target.value
      if (Number.isNaN(+value) || value > 100 || value < 1) {
        e.target.value = oldValue
        return
      }
      goodsInfo.skuNum = +e.target.value
      const num = goodsInfo.skuNum - oldValue
      await reqPostAddToCart(goodsInfo.skuId, num)
    },

    // 批量选中购物车
    async checkAll() {
      if (!this.flag) return
      this.flag = false
      const isAllChecked = +!this.isAllChecked
      await reqBatchCheckCart(this.skuIdList, isAllChecked)
      this.flag = true
      this.cartInfoList.forEach((info) => (info.isChecked = isAllChecked))
    },
    // 改变商品数量
    subOrAddGoodsNum: async function (skuId, goodsInfo, num) {
      if (!this.flag) return
      this.flag = false
      goodsInfo.skuNum += num
      await reqPostAddToCart(skuId, num)
      this.flag = true
    },
    // 批量删除商品
    async delFatchGoods() {
      let skuIdList = []
      const newInfoList = this.cartInfoList.filter((info) => {
        if (info.isChecked) {
          skuIdList.push(info.skuId)
        }
        return !info.isChecked
      })
      /* const skuIdList = this.cartInfoList.reduce((pre, cur, index) => {
        if (cur.isChecked) {
          pre.push(cur.SkuId)
        }
        return pre
       }, []) */
      if (!skuIdList.length) return
      this.$confirm('所选商品将从购物车中移除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await reqBatchDelCart(skuIdList)
          this.cartInfoList = newInfoList
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
}
</script>

<style lang="less">
.goods-active {
  background-color: #fff4e8;
}
.cart {
  width: 1200px;
  margin: 0 auto;
}
.all-goods {
  color: #e2331a;
  font-size: 16px;
}
.goods-title {
  background: #f3f3f3;
  border: 1px solid #e9e9e9;
  display: flex;
  padding: 10px;
  margin: 20px 0 20px;
}
.gt-check-all {
  display: flex;
  margin-right: 80px;
  input {
    padding-top: 3px;
    margin-right: 5px;
  }
}
.gt-goods {
  margin-right: 560px;
}
.gt-price {
  margin-right: 120px;
  text-align: center;
}
.gt-count {
  margin-right: 125px;
}
.gt-num {
  margin-right: 100px;
}
.goods-little-title {
  color: #666;
  font-weight: 700;
  padding: 10px 0 5px 15px;
  font-size: 14px;
}
.jd-dog {
  display: inline-block;
  background-image: url('./images/jd.png');
  background-repeat: no-repeat;
  width: 16px;
  height: 16px;
  margin-left: 5px;
}
.goods-content {
  border: 1px solid #f1f1f1;
  border-top: 2px solid #aaa;
  display: flex;
  padding: 15px 0 15px 40px;
  position: relative;
  margin-bottom: 10px;
  justify-content: space-around;

  img {
    width: 100px;
    height: 100px;
    border: 1px solid #aaa;
  }
}
.check-one {
  position: absolute;
  left: 12px;
  top: 18px;
}
.goods-msg {
  padding: 0 10px;
  width: 250px;
  line-height: 20px;
  overflow: hidden;
  height: 60px;
  text-overflow: ellipsis;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  margin-right: 300px;
}
.goods-price {
  line-height: 20px;
  margin-right: 100px;
}
.goods-count {
  display: flex;
  margin-right: 80px;
  input {
    width: 40px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    border: 1px solid #ccc;
    outline: none;
    box-sizing: border-box;
    margin-right: -1px;
    font-size: 14px;
  }
  button {
    box-sizing: border-box;
    width: 18px;
    outline: none;
    height: 20px;
    border: 1px solid #ccc;
    margin-right: -1px;
    cursor: pointer;
  }
}
.goods-sum {
  line-height: 20px;
  margin-right: 70px;
}
.goods-opation {
  float: right;
  margin-right: 10px;
}
.goods-opation {
  line-height: 20px;
  color: #666;
  cursor: pointer;
}
.goods-settlement {
  box-sizing: border-box;
  height: 50px;
  line-height: 50px;
  display: flex;
  justify-content: space-between;
  border: 1px solid #f0f0f0;
  margin: 20px 0;
  padding-left: 12px;
  font-size: 14px;
}
.settlement-left,
.settlement-right {
  display: flex;
}
.settlement-left div {
  display: flex;
  input {
    margin-right: 2px;
  }
}
.settlement-right {
  button {
    border: none;
    outline: none;
    background-color: #e54346;
    height: 52px;
    width: 90px;
    font-size: 16px;
    font-weight: 700;
    color: #fff;
    position: absolute;
    top: -2px;
  }
  span {
    color: #e2331a;
    font-weight: 700;
    font-size: 16px;
  }
}
.settlement-button {
  height: 50px;
  position: relative;
  width: 90px;
  margin-left: 15px;
}
.settlement-del {
  margin-left: 15px;
  cursor: pointer;
  color: #666;
  &:hover {
    color: #e2331a;
  }
}
.empty {
  text-align: center;
  h3 {
    font-size: 20px;
    color: #666;
    padding-left: 77px;
  }
  img {
    width: 300px;
  }
}
</style>
